package xyz.cerberu.cet.global.utils;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * @author β世界
 * Created on 9:48
 * @Description 文件工具
 */
public class FileUtils {
    private final static int DEFAULT_LENGTH = 3;

    /**
     * @author β世界 on 12:29 2021/3/31
     * 用于检查文件类型是否符合需求
     * @param headType: 文件类型的数组
     * @param inputStream: 文件读取流
     * @return boolean
     **/
    public static boolean checkFileType(InputStream inputStream,String... headType) throws IOException {
        byte[] header = new byte[DEFAULT_LENGTH];
        try {
            IOUtils.read(inputStream,header);
            String str = bytesToHexString(header);
            List<String> headerTypeList = Arrays.asList(headType);
            return headerTypeList.contains(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @author β世界 on 13:37 2021/3/31
     * 用于检查文件类型是否符合需求
     * @param data: 数据的byte数组
     * @param headType: 文件类型数组
     * @return boolean
     **/
    public static boolean checkFileType(byte[] data,String... headType){
        byte[] header = Arrays.copyOf(data,DEFAULT_LENGTH);
        String str = bytesToHexString(header);
        List<String> headerTypeList = Arrays.asList(headType);
        return headerTypeList.contains(str);
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}
